using dotnet_ef_admin.Src;
using dotnet_ef_admin.Src.Extensions;
using dotnet_ef_admin.Src.Filters;
using dotnet_ef_admin.Src.Utilities;

using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;

using StackExchange.Redis;

using System.Text.Json.Serialization;

var builder = WebApplication.CreateSlimBuilder(args);

// 在服务集合中添加Controllers
builder.Services.AddControllers(options => { options.Filters.Add<TransformActionFilter>(); });

// 在服务集合中添加SwaggerGen，用于生成Swagger文档
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

// 在服务集合中添加DbContext，DbContext将负责与数据库的交互
builder.Services.AddDbContext<DbCtx>(options => {
    options.UseSqlite(builder.Configuration.GetConnectionString("DefaultConnection"));
});

// 在服务集合中添加MyServices，MyServices中包含需要注入的服务
builder.Services.AddMyServices(builder.Configuration);

// 在服务集合中添加MemoryCache，用于存储并获取键值对
// builder.Services.AddMemoryCache();

// 读取配置文件中的 Redis 连接字符串
var redisConnectionString = builder.Configuration.GetConnectionString("RedisConnection");

// 确保 Redis 连接字符串不为空
if (string.IsNullOrEmpty(redisConnectionString)) throw new ArgumentException("Redis connection string is missing.");

// 配置 Redis 连接
builder.Services.AddSingleton<IConnectionMultiplexer>(sp => {
    var configurationOptions = ConfigurationOptions.Parse(redisConnectionString);
    configurationOptions.AbortOnConnectFail = false;
    return ConnectionMultiplexer.Connect(configurationOptions);
});

// 版本控制
// 在服务集合中添加EndpointsApiExplorer服务，用于支持API版本探索和文档生成
builder.Services.AddEndpointsApiExplorer();

// 在服务集合中添加API版本控制服务，并配置默认及行为选项
builder.Services.AddApiVersioning(options => {
    // 设置默认的API版本为1.0
    options.DefaultApiVersion = new ApiVersion(1, 0);
    // 当客户端未指定API版本时，假设使用默认版本
    options.AssumeDefaultVersionWhenUnspecified = true;
    // 启用在响应头中报告支持的API版本
    options.ReportApiVersions = true;
});

// 添加JWT身份验证服务
var jwtKey = builder.Configuration["Jwt:Key"];
if (string.IsNullOrEmpty(jwtKey)) throw new InvalidOperationException("配置错误: 未在设置中配置JWT密钥。");

// 创建 JwtService 实例
var jwtService = new JwtService(jwtKey);

builder.Services.AddAuthentication(options => {
    options.DefaultAuthenticateScheme = "Bearer";
    options.DefaultChallengeScheme = "Bearer";
})
    .AddJwtBearer("Bearer",
        jwtBearerOptions => {
            jwtBearerOptions.TokenValidationParameters = jwtService.GetTokenValidationParameters();
        });
builder.Services.AddAuthorization();

// 添加控制器服务并配置 JSON 选项
builder.Services.AddControllers().AddJsonOptions(options => {
    // 忽略循环依赖
    options.JsonSerializerOptions.ReferenceHandler = ReferenceHandler.IgnoreCycles;
});

var app = builder.Build();

app.UseMiddleware<ExceptionHandlingMiddleware>();

// 使用自定义中间件进行参数验证
app.UseValidateIdMiddleware();

// 启用路由系统
app.UseRouting();

app.MapControllers();

// 启用身份验证
app.UseAuthentication();

// 启用授权
app.UseAuthorization();

if (app.Environment.IsDevelopment()) {
    app.UseSwagger();
    app.UseSwaggerUI(options => { options.EnableTryItOutByDefault(); });
}

app.MapGet("/", () => "Hello World!");

app.Run();